package org.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class RedisClient {
    private JedisPool jedisPool;
    
    private static final Logger logger = LoggerFactory.getLogger(RedisClient.class);
    
    
    /**
     * <p>
     * 设置连接池
     * </p>
     * @param jedisPool
     * @since 8.0.1
     */
    public void setJedisPool(JedisPool jedisPool){
        this.jedisPool = jedisPool;
    }
    
    /**
     * <p>
     * 获取redis 资源
     * </p>
     * @return
     * @since 8.0.1
     */
    public Jedis getResource(){
        Jedis jedis=null;
        try{
            jedis = jedisPool.getResource();
        } catch(Exception e){
            logger.info("can not get redis resource "+e);
        }
        return jedis;
    }
    
    /**
     * <p>
     * 关闭redis链接
     * </p>
     * @param jedis
     * @since 8.0.1
     */
    public void disConnectRedis(Jedis jedis){
        jedis.disconnect();
    }
    
    /** 
     * 将jedis 返还连接池 
     * @param jedis 
     */  
    public void returnResource(Jedis jedis){  
        if(null != jedis){  
            try {  
                jedisPool.returnResource(jedis);  
            } catch (Exception e) {  
                logger.info("can't return jedis to jedisPool");  
            }  
        }  
    }  
    
    /**
     * <p>
     * 无法返还jedispool，释放jedis客户端对象。
     * </p>
     * @param jedis
     * @since 8.0.1
     */
    public void brokenResource(Jedis jedis){
        if(jedis != null){
            try {
                jedisPool.returnBrokenResource(jedis);
            } catch (Exception e) {
                logger.info("can't release jedis Object");
            }
        }
    }
}
